function getKey(goodsId, skuId) {
	let key = "goods-" + goodsId
	if (skuId) {
		key = "sku-" + skuId
	}
	return key
}

export function addCartBykey(cart, key, number) {
	let cartItem = cart[key]
	if(!cartItem)return
	cartItem.number += number
	return JSON.parse(JSON.stringify(cart))
}




export function addCart(cart, goods, sku, number) {
	// let cart = getCart()
	let goodsId = goods.id
	let key = getKey(goodsId, null)
	if (sku) {
		key = getKey(goodsId, sku.id)
	}
	if (cart[key]) {
		return addCartBykey(cart, key, number)
	} else {
		let goodsId = goods.id
		let oldPrice = goods.oldPrice
		let nowPrice = goods.nowPrice
		let point = goods.point
		let name = goods.name
		let img = goods.minImg
		let skuId = null
		let skuName = null
		if (sku) {
			skuId = sku.id
			skuName = sku.name
			nowPrice = sku.price
			point = sku.point
			if (sku.img) {
				img = sku.img
			}
		}
		let cartItem = {
			key,
			goodsId,
			name,
			point,
			oldPrice,
			nowPrice,
			img,
			skuId,
			skuName,
			number,
			sel: true
		}
		cart[key] = cartItem
		return JSON.parse(JSON.stringify(cart))
	}


}

//减少购物车
export function decCart(cart, goods, sku, number) {
	// let cart = getCart()
	let goodsId = goods.id
	let key = getKey(goodsId, null)
	if (sku) {
		key = getKey(goodsId, sku.id)
	}
  return	decCartByKey(cart, key, number)
}

export function decCartByKey(cart, key, number) {
	let cartItem = cart[key]
	if (cartItem) {
		if (cartItem.number - number > 0) {
			cartItem.number -= number
		} else { //直接删除
			delCart(cart, key)
		}
	}
	return JSON.parse(JSON.stringify(cart))
}





//改变购物车
export function changeCart(cart, key, number) {

	// let cart = getCart()
	let cartItem = cart[key]
	cartItem.number = number
	return JSON.parse(JSON.stringify(cart))
}

//删除购物车
export function delCart(cart, key) {
	delete cart[key]
	return JSON.parse(JSON.stringify(cart))

}

//点击购物车按钮
export function sel(cart, key) {
	// let cart = getCart()
	cart[key].sel = !cart[key].sel
	return JSON.parse(JSON.stringify(cart))
}

//选中所有
export function selAll(cart) {
	// let cart = getCart()
	Object.values(cart).forEach(item => {
		item.sel = true
	})
	return JSON.parse(JSON.stringify(cart))
	
}

//取消所有
export function cancelAll(cart) {
	// let cart = getCart()
	Object.values(cart).forEach(item => {
		item.sel = false
	})
	return JSON.parse(JSON.stringify(cart))
}

//清除所有选中的购物车
export function clear(cart) {
	// let cart = getCart()
	Object.keys(cart).forEach(key => {
		if (cart[key].sel) {
			delCart(cart, key)
		}
	})
	return JSON.parse(JSON.stringify(cart))
}

